package cn.iocoder.yudao.module.erp.controller.admin.dp;

import cn.iocoder.yudao.module.erp.controller.admin.common.DpCountQuantity;
import cn.iocoder.yudao.module.erp.dal.dataobject.dpitem.DpItemDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.dplist.DpEastListDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.dplist.DpWestListDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.finance.claim.ClaimDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.finance.pay.PayDO;
import io.swagger.v3.oas.annotations.Parameters;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.module.erp.controller.admin.dp.vo.*;
import cn.iocoder.yudao.module.erp.dal.dataobject.dp.DpDO;
import cn.iocoder.yudao.module.erp.service.dp.DpService;
import org.springframework.web.multipart.MultipartFile;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Tag(name = "管理后台 - ERP总制单")
@RestController
@RequestMapping("/erp/dp")
@Validated
public class DpController {

    @Resource
    private DpService dpService;

//    @PostMapping("/create")
//    @Operation(summary = "创建ERP总制单")
//    @PreAuthorize("@ss.hasPermission('erp:dp:create')")
//    public CommonResult<String> createDp(@Valid @RequestBody DpSaveReqVO createReqVO) {
//        return success(dpService.createDp(createReqVO));
//    }

    @PutMapping("/update")
    @Operation(summary = "更新ERP总制单")
//    @PreAuthorize("@ss.hasPermission('erp:dp:update')")
    public CommonResult<Boolean> updateDp(@Valid @RequestBody DpSaveReqVO updateReqVO) {
        dpService.updateDp(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除ERP总制单")
    @Parameter(name = "id", description = "编号", required = true)
//    @PreAuthorize("@ss.hasPermission('erp:dp:delete')")
    public CommonResult<Boolean> deleteDp(@RequestParam("id") String id) {
        dpService.deleteDp(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得ERP总制单")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
//    @PreAuthorize("@ss.hasPermission('erp:dp:query')")
    public CommonResult<DpRespVO> getDp(@RequestParam("id") String id) {
        DpDO dp = dpService.getDp(id);
        return success(BeanUtils.toBean(dp, DpRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得ERP总制单分页")
//    @PreAuthorize("@ss.hasPermission('erp:dp:query')")
    public CommonResult<PageResult<DpRespVO>> getDpPage(@Valid DpPageReqVO pageReqVO) {
        PageResult<DpDO> pageResult = dpService.getDpPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, DpRespVO.class));
    }

    @GetMapping("/selectByShipper/page")
    @Operation(summary = "根据发货人获得ERP总制单分页")
//    @PreAuthorize("@ss.hasPermission('erp:dp:query')")
    public CommonResult<PageResult<DpRespVO>> selectByShipper(@Valid DpPageReqVO pageReqVO) {
        PageResult<DpDO> pageResult = dpService.selectByShipper(pageReqVO);
        return success(BeanUtils.toBean(pageResult, DpRespVO.class));
    }

    @GetMapping("/shipperDate")
    @Operation(summary = "获得收货人数据")
//    @PreAuthorize("@ss.hasPermission('erp:dp:query')")
    public CommonResult<PageResult<DpRespVO>> shipperDate(@Valid DpPageReqVO pageReqVO) {
        PageResult<DpDO> pageResult = dpService.shipperDate(pageReqVO);
        return success(BeanUtils.toBean(pageResult, DpRespVO.class));
    }

    @GetMapping("/getDpFareCount/{shipper}")
    @Operation(summary = "根据发货人统计各金额数")
//    @PreAuthorize("@ss.hasPermission('erp:dp:query')")
    public CommonResult<DpDO> getDpFareCount(@PathVariable("shipper") String shipper) {
        DpDO dpDO = dpService.getDpFareCount(shipper);
        return success(dpDO);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出ERP总制单 Excel")
//    @PreAuthorize("@ss.hasPermission('erp:dp:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportDpExcel(@Valid DpPageReqVO pageReqVO, HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        pageReqVO.setExportStatus(1);
        List<DpDO> list = dpService.getDpPage(pageReqVO).getList();
        // 对数据进行字段处理
        List<DpRespVO> processedList = list.stream().map(dpDO -> {
            DpRespVO respVO = BeanUtils.toBean(dpDO, DpRespVO.class);
            Integer storeType = respVO.getStoreType();
            //转换仓库字段
            if (storeType != null){
                if (storeType == 1) respVO.setStoreTypeFormatted("义乌");
                if (storeType == 2) respVO.setStoreTypeFormatted("广州");
                if (storeType == 3) respVO.setStoreTypeFormatted("东宁");
                if (storeType == 4) respVO.setStoreTypeFormatted("乌鲁木齐");
                if (storeType == 5) respVO.setStoreTypeFormatted("南疆");
                if (storeType == 6) respVO.setStoreTypeFormatted("北疆");
                if (storeType == 7) respVO.setStoreTypeFormatted("东线");
            }
            // 转换核销字段
            if (dpDO.getWriteOff() != null) respVO.setWriteOffFormatted(dpDO.getWriteOff() == 1 ? "是" : "否");
            // 转换线路字段
            if (dpDO.getLine() != null) respVO.setLineFormatted(dpDO.getLine() == 1 ? "东线" : "西线");
            // 转换支付类型字段
            if (dpDO.getPayType() != null) respVO.setPayTypeFormatted(dpDO.getPayType() == 1 ? "国内支付" : "国外支付");
            // 转换金额计算类型字段
            Integer calmethod = dpDO.getCalmethod();
            if (calmethod != null){
                if (calmethod == 1) respVO.setCalmethodFormatted("按重量");
                if (calmethod == 2) respVO.setCalmethodFormatted("按立方");
                if (calmethod == 3) respVO.setCalmethodFormatted("按整车");
                if (calmethod == 4) respVO.setCalmethodFormatted("按重量和立方");
                if (calmethod == 5) respVO.setCalmethodFormatted("垫付加运费");
            }
            return respVO;
        }).collect(Collectors.toList());
        // 求和
        double totalAmountSum = processedList.stream().mapToDouble(DpRespVO::getTotalAmount).sum();
        double receivedFareSum = processedList.stream().mapToDouble(DpRespVO::getReceivedFare).sum();
        double debtTotalSum = processedList.stream().mapToDouble(DpRespVO::getDebtTotal).sum();
        double claimAmountSum = processedList.stream().mapToDouble(DpRespVO::getClaimAmount).sum();

        DpRespVO dpRespVO = new DpRespVO();
        dpRespVO.setId("合计");
        dpRespVO.setTotalAmount((totalAmountSum-claimAmountSum));
        dpRespVO.setReceivedFare(receivedFareSum);
        dpRespVO.setDebtTotal(debtTotalSum);
        processedList.add(dpRespVO);

        // 创建提示信息行，并将其添加到列表末尾
        DpRespVO footerRow = new DpRespVO();
        footerRow.setId("注意：" +
                "一：提货时双方当面交接清楚，如货物提走后发现损坏少货现象本公司不负责。\n" +
                "二：预期不提货者，产生一切费用及后果由客户自己承担。\n" +
                "三：易碎的货物在承运过程中发现破碎、丢失时，只赔偿丢失的货物，不赔偿破损的货物。\n" +
                "义乌库房地址:浙江省义乌市苏溪高君路7号(浙江博尼锦纶服份有限公司西)大门进去直走100米311库房 电话/Tel:15600000311(微信同号)\n" +
                "广州库房地址:广东省佛山市南海区里水镇河塱沙里水东部工业园10号南海毛中厂二期(东侧大院311库房) 电话/Te1:18500000311(微信同号)\n" +
                "新疆库房地址:新疆维吾尔自治区乌鲁木齐市沙依巴克区青葱路1048号附1号楼311库 电话/Te1:18199990311(微信同号)");
        // 将提示信息添加到列表末尾
        processedList.add(footerRow);
        // 导出 Excel
        ExcelUtils.write(response, "ERP总制单.xls", "数据", DpRespVO.class, processedList);
    }

    @GetMapping("/outstroe/get-import-template")
    @Operation(summary = "获得出库导入的制单模板")
    public void importTemplate(HttpServletResponse response) throws IOException {
        // 手动创建导出 demo
        List<DpIdImportExcelVO> list = new ArrayList<>();
        // 输出
        ExcelUtils.write(response, "出库导入模板.xls", "出库列表", DpIdImportExcelVO.class, list);
    }

    @GetMapping("/DpList/get-import-template")
    @Operation(summary = "获得制单导入的模板")
    public void DpListimportTemplate(HttpServletResponse response) throws IOException {
        // 手动创建导出 demo
        List<DpImportExcelVO> list = new ArrayList<>();
        // 输出
        ExcelUtils.write(response, "制单导入模板.xls", "制单列表", DpImportExcelVO.class, list);
    }

//    @PostMapping("/outstroe/import")
//    @Operation(summary = "出库导入")
//    @Parameters({
//            @Parameter(name = "file", description = "Excel 文件", required = true),
//            @Parameter(name = "updateSupport", description = "是否支持更新，默认为 false", example = "true")
//    })
//    public CommonResult<Boolean> importExcel(@RequestParam("storeType") Integer storeType,
//                                             @RequestParam("file") MultipartFile file,
//                                             @RequestParam(value = "updateSupport", required = false, defaultValue = "false") Boolean updateSupport) throws Exception {
//        List<DpIdImportExcelVO> list = ExcelUtils.read(file, DpIdImportExcelVO.class);
//        return success(dpService.importUserList(storeType, list, updateSupport));
//    }


    @PostMapping("/outstroe/import")
    @Operation(summary = "出库导入")
    @Parameters({@Parameter(name = "file", description = "Excel 文件", required = true)})
    public CommonResult<List<String>> importExcel(@RequestParam("file") MultipartFile file) throws Exception {
        List<DpIdImportExcelVO> list = ExcelUtils.read(file, DpIdImportExcelVO.class);
        List<String> ids = list.stream()
                .map(DpIdImportExcelVO::getId)
                .filter(Objects::nonNull) // 过滤掉 null 值
                .collect(Collectors.toList());
        return success(ids);
    }

//    @GetMapping("/outstroe/export")
//    @Operation(summary = "出库列表导出Excel")
//    @ApiAccessLog(operateType = EXPORT)
//    public void exportExcel(@RequestParam("storeType") Integer storeType,
//                            @RequestParam("ids") List<String> ids,
//                            HttpServletResponse response) throws IOException {
//        List<DpOutStoreRespVo> processedList = dpService.selectDpByids(storeType,ids);
//        // 导出 Excel
//        ExcelUtils.write(response, "ERP出库列表导出.xls", "数据", DpOutStoreRespVo.class, processedList);
//    }

    @PostMapping("/outstroe/export")
    @Operation(summary = "出库列表导出Excel")
    @ApiAccessLog(operateType = EXPORT)
    public void exportExcel(@RequestBody DpPageReqVO reqVO,HttpServletResponse response) throws IOException {
        List<DpOutStoreRespVo> processedList = dpService.selectDpByids(reqVO.getStoreType(), reqVO.getIds());
        // 导出 Excel
        ExcelUtils.write(response, "ERP出库列表导出.xls", "数据", DpOutStoreRespVo.class, processedList);
    }

    @PostMapping("/DpList/import")
    @Operation(summary = "制单导入")
    @Parameters({
            @Parameter(name = "file", description = "Excel 文件", required = true),
            @Parameter(name = "updateSupport", description = "是否支持更新，默认为 false", example = "true")
    })
    public CommonResult<Boolean> DpListImportExcel(@RequestParam("storeType") Integer storeType,
                                             @RequestParam("file") MultipartFile file,
                                                   @RequestParam("line") Integer line,
                                             @RequestParam(value = "updateSupport", required = false, defaultValue = "false") Boolean updateSupport) throws Exception {
        List<DpImportExcelVO> list = ExcelUtils.read(file, DpImportExcelVO.class);
        return success(dpService.importDpList(storeType,line, list, updateSupport));
    }


    @PutMapping("/examine")
    @Operation(summary = "ERP总物流单据审核反审核")
//    @PreAuthorize("@ss.hasPermission('erp:dp:examine')")
    public CommonResult<Boolean> examineDp(@RequestBody DpPageReqVO pageReqVO){
        dpService.examineDp(pageReqVO);
        return success(true);
    }

    @PostMapping("/dpReturn/{id}")
    @Operation(summary = "根据运单号回退单据至对应制单仓库")
//    @PreAuthorize("@ss.hasPermission('erp:dp:dpreturn')")
    public CommonResult<Boolean> dpReturn(@PathVariable String id) {
        dpService.dpReturn(id);
        return success(true);
    }

    @GetMapping ("/dpPickUp")
    @Operation(summary = "ERP国外仓库全部签收")
//    @PreAuthorize("@ss.hasPermission('erp:dp:pickup')")
    public CommonResult<Integer> dpPickUp(@RequestParam("tableName") String tableName, @RequestParam("id") String id, @RequestParam("pickStatus") Integer pickStatus,@RequestParam("signNum") Integer signNum,@RequestParam("signStatus") Integer signStatus) {
        Integer count = dpService.dpPickUp(tableName, id,pickStatus,signNum,signStatus);
        return success(count);
    }

    // ==================== 子表（总东线清单） ====================

    @GetMapping("/dp-east-list/list-by-no")
    @Operation(summary = "获得总东线清单列表")
    @Parameter(name = "no", description = "运单号")
//    @PreAuthorize("@ss.hasPermission('erp:dp:detail')")
    public CommonResult<List<DpEastListDO>> getDpEastListListByNo(@RequestParam("no") String no) {
        return success(dpService.getDpEastListListByNo(no));
    }

    // ==================== 子表（总西线清单） ====================

    @GetMapping("/dp-west-list/list-by-no")
    @Operation(summary = "获得总西线清单列表")
    @Parameter(name = "no", description = "运单号")
//    @PreAuthorize("@ss.hasPermission('erp:dp:detail')")
    public CommonResult<List<DpWestListDO>> getDpWestListListByNo(@RequestParam("no") String no) {
        return success(dpService.getDpWestListListByNo(no));
    }

    // ==================== 子表（ERP总制单货号详情） ====================

    @GetMapping("/dp-item/list-by-no")
    @Operation(summary = "获得ERP总制单货号详情列表")
    @Parameter(name = "no", description = "运单号")
//    @PreAuthorize("@ss.hasPermission('erp:dp:detail')")
    public CommonResult<List<DpItemDO>> getDpItemListByNo(@RequestParam("no") String no) {
        return success(dpService.getDpItemListByNo(no));
    }

    @GetMapping("/getDpCountQuantity")
    @Operation(summary = "ERP总制单数据统计")
    public CommonResult<DpCountQuantity> getDpCountQuantity(){
        DpCountQuantity dpCountQuantity = dpService.getDpCountQuantity();
        return success(dpCountQuantity);
    }

    @GetMapping("/searchSipperDpList")
    @Operation(summary = "搜索发货人总制单列表")
//    @PreAuthorize("@ss.hasPermission('erp:dp:detail')")
    public CommonResult<List<DpDO>> searchSipperDpList(@RequestParam("shipper") String shipper,
                                                       @RequestParam(value = "no", required = false) String no,
                                                       @RequestParam(value = "prepaidStatus", required = false) Integer prepaidStatus) {
        return success(dpService.searchSipperDpList(shipper, no, prepaidStatus));
    }

    @PostMapping("/dpPay")
    @Operation(summary = "ERP运费付款")
//    @PreAuthorize("@ss.hasPermission('erp:dp:detail')")
    public CommonResult<Boolean> dpPay(@Valid @RequestBody PayDO payDO) {
        dpService.dpPay(payDO);
        return success(true);
    }

    @PostMapping("/dpClaim")
    @Operation(summary = "ERP运费赔付")
//    @PreAuthorize("@ss.hasPermission('erp:dp:detail')")
    public CommonResult<Boolean> dpClaim(@Valid @RequestBody ClaimDO claimDO) {
        dpService.dpClaim(claimDO);
        return success(true);
    }

}